<?php

//MODIFY AFTER SEARCH IS DEBUGGED
//set required scripts
require("HTMLFunctions.php");
require("ValidationFunctions.php");
require('ac_db.inc.php');

//set error reporting
error_reporting(E_ERROR | E_WARNING);

//set credentials for database
setcredentials("tr2286","databases8620", "w4111b.cs.columbia.edu/ADB");

//create DB instance
$db = new Db("Proj1", "Part3");

//set email as permanent variable as it will be constantly used
$email;
$ticker;
$errorText = "";
$price;

//make sure nobody arrived here illegaly
if(count($_POST) == 0){
	
	//if so, redirect to login
	echo "<meta http-equiv='refresh' content='0;url=http://localhost/login.php'>";
	exit;
}
//see if first access or trade that is passed back
elseif(count($_POST) == 2){
	
	//otherwise an email and a ticker will be passed
	$email = $_POST['email'];
	$ticker = $_POST['ticker'];
	$price = $_POST['price'];
	
	
	//call method to show trading platform
	showTradeSite($email, $errorText, $ticker, $price, $db);
}
//otherwise process the trade
else{
	
	//otherwise an email and a ticker will be passed
	$email = $_POST['email'];
	$ticker = $_POST['ticker'];
	$price = $_POST['price'];
	
	//determine if bought our sold
	if($_POST['buyQuantity'] != null){
		
		processBuy($email, $ticker, $errorText, $price, $db);
	}
	else{
		processSell($email, $ticker, $errorText, $price, $db);
	}
	
}

//function to process buying
function processBuy($email, $ticker, $errorText, $price, $db){
	
	$quantity = $_POST['buyQuantity'];
	//$currentPrice = $db->getCurrentStockValue($ticker);
	$currentPrice = $price;
	$balance = $db->getLiquidBalance($email);
	
	//ensure that user has enough money
	$totalCost = ($quantity * $currentPrice);
	
	//ensure it is a number
	if(!ValidationFunctions::validatePhone($quantity)){
		
		//set error and redisplay the trade form
		$errorText = "<h4><font color=\"red\">Your entry is invalid.<br>Please try again.</font></h4>";
		showTradeSite($email, $errorText, $ticker, $price, $db);
	}
	
	//ensure it is greater than 0
	elseif($quantity <= 0){
		
		//set error and redisplay the trade form
		$errorText = "<h4><font color=\"red\">You entered a negative number or 0.<br>Please try again.</font></h4>";
		showTradeSite($email, $errorText, $ticker, $price, $db);
	}
	
	elseif($totalCost > $balance){
		
		//set error and redisplay the trade form
		$errorText = "<h4><font color=\"red\">Your trade exceeds your balance.<br>Please try again.</font></h4>";
		showTradeSite($email, $errorText, $ticker, $db);
	}
	else{
		
		//trade is valid#
		echo "before transaction table";
		$transactionID = $db->newTransaction($quantity, $price, 1);
		
				echo "before activity table";
		
		//now that transaction is created, add to the activity table
		$db->newActivity($email, $ticker, $transactionID);
		
				echo "before balance table";
		
		//set correct new balance
		$newBalance = ($balance - $totalCost);
		$db->setLiquidBalance($email, $newBalance);
		
		//call function to show success
		showSuccess($email, $ticker, $quantity, "bought", $db);
	}
}

//function to process selling
function processSell($email, $ticker, $errorText, $price, $db){
	
	$quantity = $_POST['buyQuantity'];
	//$currentPrice = $db->getCurrentStockValue($ticker);
	$currentPrice = $price;
	$sharesOwned = $db->getShareQuantity($email, $ticker);
	
	//ensure it is a number
	if(!ValidationFunctions::validatePhone($quantity)){
		
		//set error and redisplay the trade form
		$errorText = "<h4><font color=\"red\">Your entry is invalid.<br>Please try again.</font></h4>";
		showTradeSite($email, $errorText, $ticker, $db);
	}
	
	//ensure it is greater than 0
	elseif($quantity <= 0){
		
		//set error and redisplay the trade form
		$errorText = "<h4><font color=\"red\">You entered a negative number or 0.<br>Please try again.</font></h4>";
		showTradeSite($email, $errorText, $ticker, $db);
	}
	
	elseif($quantity > $sharesOwned){
		
		//set error and redisplay the trade form
		$errorText = "<h4><font color=\"red\">You attempted to sell more stocks than you own.<br>Please try again.</font></h4>";
		showTradeSite($email, $errorText, $ticker, $db);
	}
	else{
		
		//trade is valid
		$quantity = ($quantity * -1);
		$transactionID = $db->newTransaction($quantity, $price, 0);
		
		$quantity = ($quantity * -1); 
		//now that transaction is created, add to the activity table
		$db->newActivity($email, $ticker, $transactionID);
		
		//set correct new balance
		$newBalance = $balance + ($currentPrice * $quantity);
		$db->setLiquidBalance($email, $newBalance);
		
		//call function to show success
		showSuccess($email, $ticker, $quantity, "sold", $db);
	}
}

//function to show successful completion of a trade
function showSuccess($email, $ticker, $quantity, $buySell, $db){
	
	//call method to display html beginnign
	HTMLFunctions::printHTMLHead("Successfully Traded!");
	
	HTMLFunctions::generateTitleBar("You successfully booked a trade!",$email, $db);
	
	echo <<<END_HTML
	
	<!--now display the message to the user-->
	<h4>You can see the effects of your activity in your profile.</h4>
	<br>
	
END_HTML;

	//create array for button
	$parameterArray = array();
	$parameterArray['email'] = $email;
	
	//call subroutine to display button that returns the user to the profile
	HTMLFunctions::generateButton("profile.php", "Go To profile", $parameterArray);

	$db->closeSession();
	
	//now call method to produce closing html tags
	HTMLFunctions::printHTMLEnd();
	
	
}

//funciton to create the html code for the trade site
function showTradeSite($email, $errorText, $ticker, $db){
	
	//create the html beginning
	HTMLFunctions::printHTMLHead("Trade $ticker");
	
	//create header bar
	HTMLFunctions::generateTitleBar("Your Profile", $email, $db);
	
	//call function to create the profile html
	generateTradeHTML($email, $errorText, $ticker, $db);
	
	$db->closeSession();
	
	//call function to create the end
	HTMLFunctions::printHTMLEnd();
}

function generateTradeHTML($email, $errorText, $ticker, $db){
	
	//first print the error
	echo "$errorText";
	
	//now create the table to both buy and sell stocks
	//print heading code
	echo <<<END_HTML
	
	<!--now proceed to main body-->
	<div class="content">
	<table class="tablecontent">
	<tr class="trmain">
	<td class="tdmain">
	<div class="tdmaindiv">
	
	<!--Buy information-->
	<h4>Buy:</h4>
END_HTML;

	//GENERATE_BUY_HTML
	echo <<<END_HTML
	<table>
		<form action="tradeStock.php" method=POST>
			<tr>
				<!-- amount-->
				<td><p>Number of Shares:*</p></td>
				<td><input type="text" name="buyQuantity""></td>
			</tr>
				<input type="hidden" name="email" value="$email">
				<input type="hidden" name="ticker" value="$ticker">
			<tr>
				<!-- submit button-->
				<td><br><input type="submit" value="Buy"></form></td>
			</tr
			<!-- now create a hidden field that resubmits the email so that the script knows what user is being passed back-->
			
	</table>

END_HTML;
		
	//print more HTML
	echo <<<END_HTML
	</div>
	</td>
	<td class="tdmain">
	<div class="tdmaindiv">
	
	<!--sell -->
	<h4>Sell:</h4>
	
END_HTML;

	//GENERATE SELL HTML
	
	echo <<<END_HTML
	<table>
		<form action="tradeStock.php" method=POST>
			<tr>
				<!-- amount-->
				<td><p>Number of Shares:*</p></td>
				<td><input type="text" name="sellQuantity""></td>
			</tr>
				<input type="hidden" name="email" value="$email">
				<input type="hidden" name="ticker" value="$ticker">
			<tr>
				<!-- submit button-->
				<td><br><input type="submit" value="Sell"></form></td>
			</tr
	</table>
	
END_HTML;
		
	//print more HTML
	echo <<<END_HTML
	
	</div>
	</td>
	</table>
	</div>

END_HTML;
	
	
}




